package com.lenovo.mso2o.ui.fragment;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.lenovo.framework.base.InjectableDialogFragment;
import com.lenovo.framework.util.DLog;
import com.lenovo.mso2o.MSApplication;
import com.lenovo.mso2o.R;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import butterknife.OnClick;

/**
 * Created by hippo on 2015/4/22 0022.
 */
public class WritePadDialogFragment extends InjectableDialogFragment{

    public static final int WRITE_PAD = 0x5c;
    WindowManager.LayoutParams p ;

    static final int BACKGROUND_COLOR = Color.WHITE;

    static final int BRUSH_COLOR = Color.BLACK;

    PaintView mView;
    public boolean writed = false;

    /** The index of the current color to use. */
    int mColorIndex;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);

        //getDialog().getWindow().setAttributes(p);
        mView = new PaintView(getContext().getApplicationContext());
        FrameLayout frameLayout = (FrameLayout) view.findViewById(R.id.tablet_view);
        frameLayout.addView(mView);
        mView.requestFocus();
        return view;
    }

    @OnClick(R.id.tablet_clear)
    public void onClear(View view){
        mView.clear();
    }

    @OnClick(R.id.tablet_ok)
    public void onOK(View view){
        if(!writed) {
            Toast.makeText(getContext(), getString(R.string.please_write_sth), Toast.LENGTH_SHORT).show();
            return;
        }
        try {
            String path = createFile();
            WritePadDialogFragment.this.dismiss();
            Bundle b = new Bundle();
            b.putString("path", path);
            mInterface.onRetrieveDialogFragmentData(b, WRITE_PAD);
        } catch (Exception e) {
            DLog.p(e);
        }
    }

    @OnClick(R.id.tablet_cancel)
    public void onCancel(View view){
        getDialog().cancel();
    }

    @Override
    public int provideContentRes() {
        return R.layout.write_pad;
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    /**
     * 创建手写签名文件
     *
     * @return
     */
    private String createFile() {
        ByteArrayOutputStream baos = null;
        String _path = null;
        try {
            String sign_dir = MSApplication.getDataDir() + File.separator;
            _path = sign_dir + "signature_" + System.currentTimeMillis() + ".jpg";
            baos = new ByteArrayOutputStream();
            mView.getCachebBitmap().compress(Bitmap.CompressFormat.JPEG, 100, baos);
            byte[] photoBytes = baos.toByteArray();
            if (photoBytes != null) {
                FileOutputStream outputStream = new FileOutputStream(new File(_path));
                outputStream.write(photoBytes);
                outputStream.close();
            }

        } catch (IOException e) {
            DLog.p(e);
        } finally {
            try {
                if (baos != null)
                    baos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return _path;
    }

    @Override
    protected void onFragmentInVisible(Bundle savedInstanceState) {

    }

    @Override
    protected void onFragmentVisible(Bundle savedInstanceState) {

    }

    /**
     * This view implements the drawing canvas.
     *
     * It handles all of the input events and drawing functions.
     */
    class PaintView extends View {
        private Paint paint;
        private Canvas cacheCanvas;
        private Bitmap cachebBitmap;
        private Path path;

        public Bitmap getCachebBitmap() {
            return cachebBitmap;
        }

        public PaintView(Context context) {
            super(context.getApplicationContext());
            init();
        }

        private void init(){
            paint = new Paint();
            paint.setAntiAlias(true);
            paint.setStrokeWidth(4);
            paint.setStyle(Paint.Style.STROKE);
            paint.setColor(Color.BLACK);
            path = new Path();
            getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    p = getDialog().getWindow().getAttributes();  //获取对话框当前的参数值
                    cachebBitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.RGB_565);
                    cacheCanvas = new Canvas(cachebBitmap);
                    cacheCanvas.drawColor(Color.WHITE);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                        getViewTreeObserver().removeOnGlobalLayoutListener(this);
                    }else{
                        getViewTreeObserver().removeGlobalOnLayoutListener(this);
                    }
                }
            });
        }

        public void clear() {
            if (cacheCanvas != null) {
                writed = false;
                paint.setColor(BACKGROUND_COLOR);
                cacheCanvas.drawPaint(paint);
                paint.setColor(Color.BLACK);
                cacheCanvas.drawColor(Color.WHITE);
                invalidate();
            }
        }



        @Override
        protected void onDraw(Canvas canvas) {
            // canvas.drawColor(BRUSH_COLOR);
            canvas.drawBitmap(cachebBitmap, 0, 0, null);
            canvas.drawPath(path, paint);
        }

        @Override
        protected void onSizeChanged(int w, int h, int oldw, int oldh) {

            int curW = cachebBitmap != null ? cachebBitmap.getWidth() : 0;
            int curH = cachebBitmap != null ? cachebBitmap.getHeight() : 0;
            if (curW >= w && curH >= h) {
                return;
            }

            if (curW < w)
                curW = w;
            if (curH < h)
                curH = h;

            Bitmap newBitmap = Bitmap.createBitmap(curW, curH, Bitmap.Config.RGB_565);
            Canvas newCanvas = new Canvas();
            newCanvas.setBitmap(newBitmap);
            if (cachebBitmap != null) {
                newCanvas.drawBitmap(cachebBitmap, 0, 0, null);
            }
            cachebBitmap = newBitmap;
            cacheCanvas = newCanvas;
        }

        private float cur_x, cur_y;

        @Override
        public boolean onTouchEvent(MotionEvent event) {

            float x = event.getX();
            float y = event.getY();

            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN: {
                    cur_x = x;
                    cur_y = y;
                    path.moveTo(cur_x, cur_y);
                    break;
                }

                case MotionEvent.ACTION_MOVE: {
                    writed = true;
                    path.quadTo(cur_x, cur_y, x, y);
                    cur_x = x;
                    cur_y = y;
                    break;
                }

                case MotionEvent.ACTION_UP: {
                    cacheCanvas.drawPath(path, paint);
                    path.reset();
                    break;
                }
            }

            invalidate();

            return true;
        }
    }
}
